<template>
  <div class="rent_main">
    <div class="text_content">
      <textarea @keyup="writeContent" @input="writeContent" name="" id="" :placeholder="holder" cols="30" rows="10" v-model="value"
                maxlength="200" @change="passValue"></textarea>
      <div class="count">
        {{currentCount}}/{{totalCount-currentCount}}
      </div>
    </div>
    <div class="vue-upload-img-multiple">
      <ul>
        <li v-show="image && !isIOS" v-for="(image,index) in images.localId" :key="index">
          <div class="img_size">
            <div :style="'backgroundImage:url('+image+')'" class="picture" @click="preview(index)"></div>
            <span @click='delImage(index)' class="remove">x</span>
          </div>
        </li>
        <li v-show="image && isIOS" v-for="(image,index) in images.iosLocalId" :key="index">
          <div class="img_size">
            <div :style="'backgroundImage:url('+image+')'" class="picture" @click="preview(index)"></div>
            <span @click='delImageIOS(index)' class="remove">x</span>
          </div>
        </li>
        <li class="input-container" @click="addImage()"></li>
      </ul>
    </div>
    <div class="prompt">
      <span>（不能超过6张图片）</span>
    </div>
  </div>
</template>
<style lang="scss">
  @import "../../common/sass/base.scss";
  .mint-indicator-mask {
    top: 0;
    left: 0;
    position: fixed;
    width: 100%;
    height: 100%;
    opacity: 0.5;
    background: #000;
    z-index: 667;
  }
  .rent_main {
    width: 100%;
    /*padding-top: 40px;*/
    background-color: #fff;
    .text_content {
      padding: 10px;
      position: relative;
      .mint-cell:first-child .mint-cell-wrapper {
        background-color: #f2f2f2;
        border-radius: 6px;
        .mint-field-core {
          resize: none;
          background-color: #f2f2f2;
          font-size: 14px;
        }
      }
      textarea {
        box-sizing: border-box;
        width: 100%;
        padding: 10px;
        height: 120px;
        background: #f2f2f2;
        border-radius: 5px;
        resize: none;
        outline: none;
        border: none;
        font-size: 14px;
      }
      .count {
        position: absolute;
        bottom: 20px;
        right: 20px;
        color: #0078de;
      }
    }
    .vue-upload-img-multiple {
      width: 100%;
      height: 100%;
      padding: 0 10px 10px;
      box-sizing: border-box;
      display: inline-block;
      ul {
        display: flex;
        flex-wrap: wrap;
        li {
          width: 25%;
          margin-top: 5px;
          text-align: center;
          .loading {
            display: block;
            margin: 0 auto;
            margin-top: 20px;
          }
          .img_size {
            display: inline-block;
            position: relative;
            .picture {
              width: 70px;
              height: 70px;
              float: left;
              border-radius: 4px;
              background-position: center center;
              background-repeat: no-repeat;
              background-size: cover;
            }
            .remove {
              position: absolute;
              top: -6px;
              right: -4px;
              width: 18px;
              height: 18px;
              z-index: 11;
              line-height: 18px;
              text-align: center;
              border-radius: 50%;
              background-color: red;
              color: #fff;
              font-size: 15px;
            }
          }
        }
        .input-container {
          display: inline-block;
          background: url('../common/images/tianjiatupian@2x.png') no-repeat;
          width: 70px;
          height: 70px;
          background-size: 100% 100%;
          text-align: center;
        }
      }
    }
    .prompt {
      width: 100%;
      height: 30px;
      text-align: left;
      span {
        font-size: 13px;
        line-height: 30px;
        color: red;
        margin-left: 1px;
      }
    }
  }
</style>
<script>
  import { Toast } from 'mint-ui'
  import wx from 'weixin-js-sdk'
  import commonUrl from '../../common/js/commonUrl.js'
  import qs from 'qs'
  export default {
    data () {
      return {
        value: '',
        images: {
          localId: [],
          iosLocalId: []
        },
        maxSize: 0,
        ready: false,
        isIOS: false,
        serverId: [],
        totalCount: 200,
        currentCount: 0
      }
    },
    props: ['holder'],
    created () {
      // 初始化JSConfig
      const urlLink = `${commonUrl.apihost}index.php/wx/wx_jssdk/getSignPackage`
      var data = {
        url: window.location.href.split('#')[0]
      }
      this.$http.post(urlLink, qs.stringify(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
        if (res.data.code === 200) {
          wx.config({
            debug: false,
            appId: res.data.data.appId,
            nonceStr: res.data.data.nonceStr,
            rawString: res.data.data.rawString,
            signature: res.data.data.signature,
            timestamp: res.data.data.timestamp,
            jsApiList: ['chooseImage', 'previewImage', 'getLocalImgData', 'uploadImage']
          })
          this.ready = true
        }
      })
    },
    methods: {
      writeContent() {
        this.currentCount = this.value.length
        let remainCount = this.totalCount - this.currentCount
        if (!remainCount) {
          Toast({
            message: '字数不能超过200',
            position: 'middle',
            duration: 1000
          })
        }
      },
      passValue() {
        this.$emit('getValue', this.value)
      },
      addImage () {
        if (this.ready) {
          var self = this
          var currentSize = this.images.localId.length
          if (self.isIOS) {
            if (this.images.iosLocalId.length > 5) {
              Toast({
                message: '图片不能超过6张',
                position: 'middle',
                duration: 1000
              })
              return
            }
          } else {
            if (this.images.localId.length > 5) {
              Toast({
                message: '图片不能超过6张',
                position: 'middle',
                duration: 1000
              })
              return
            }
          }
          wx.chooseImage({
            count: 6 - currentSize, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              self.images.localId = self.images.localId.concat(res.localIds)
              if (window.__wxjs_is_wkwebview) {
                self.isIOS = true
                function readImages () {
                  wx.getLocalImgData({
                    localId: self.images.localId[currentSize],
                    success: function (res) {
                      var localData = res.localData
                      localData = localData.replace('jgp', 'jpeg')
                      self.images.iosLocalId.push(localData)
                      currentSize++
                      if (currentSize < self.images.localId.length) {
                        readImages()
                      }
                    },
                    fail: (res) => {
                      alert(res.errMsg)
                    }
                  })
                }
                readImages()
              }
              self._upload(currentSize)
            },
            fail: (err) => {
              console.log(err)
            }
          })
        }
      },
      _upload(i) {
        // var localId = localIds.shift()
        wx.uploadImage({
          localId: this.images.localId[i], // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: (res) => {
            i++
            this.serverId.push(res.serverId) // 返回图片的服务器端ID
            this.$emit('getImage', this.serverId)
            if (i < this.images.localId.length) {
              setTimeout(() => {
                this._upload(i)
              }, 100)
            }
          }
        })
      },
      delImage (index) {
        this.images.localId.splice(index, 1)
        this.serverId.splice(index, 1)
        this.$emit('getImage', this.serverId)
      },
      delImageIOS (index) {
        this.images.iosLocalId.splice(index, 1)
        this.images.localId.splice(index, 1)
        this.serverId.splice(index, 1)
        this.$emit('getImage', this.serverId)
      },
      preview (index) {
        wx.previewImage({
          current: this.images.localId[index], // 当前显示图片的http链接
          urls: this.images.localId // 需要预览的图片http链接列表
        })
      }
    }
  }
</script>
